import 'dart:ui';

import 'package:aweb5/Constants.dart';
import 'package:aweb5/generated/json/common_result_entity_helper.dart';
import 'package:aweb5/pages/registry_success.dart';
import 'package:aweb5/util/DialogUtil.dart';
import 'package:aweb5/util/NaviUtil.dart';
import 'package:flutter/material.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:aweb5/style.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:aweb5/custom/LoginFormCode.dart';
import 'package:aweb5/util/toast_util.dart';
import 'package:aweb5/util/HttpClient.dart';
import 'package:aweb5/config/Config.dart';
import 'package:aweb5/util/StringUtil.dart';
import 'package:aweb5/util/toast_util.dart';
//import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_picker/image_picker.dart';
import 'package:load/load.dart';
import 'package:aweb5/bean/aplus/common_result_entity.dart';
import 'dart:io';
import 'package:aweb5/bean/aplus/upload_entity.dart';
import 'package:aweb5/generated/json/upload_entity_helper.dart';

class Reigistry extends StatefulWidget {
  @override
  _ReigistryState createState() => _ReigistryState();
}

class _ReigistryState extends State<Reigistry> {
  TextEditingController phoneContr = TextEditingController();
  TextEditingController virifyContr = TextEditingController();
  TextEditingController nameContr = TextEditingController();
  TextEditingController numContr = TextEditingController();
  bool hasSendCode = false;
  String screenShot = "";
  String codeShot = "";
  bool isVideo = false;
  final ImagePicker _picker = ImagePicker();
  BuildContext context;
  bool screen = false;
  bool code = false;

  @override
  Widget build(BuildContext context) {
    this.context = context;
    return Scaffold(
      body: SafeArea(
          child: Container(
        padding: EdgeInsets.all(ScreenUtil().setWidth(20)),
        child: Column(
//          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Row(
              children: <Widget>[
                Text(
                  "手机号",
                  style: TextStyle(
                      color: textColor10,
                      fontSize: ScreenUtil().setSp(16),
                      fontWeight: FontWeight.bold),
                ),
                SizedBox(
                  width: ScreenUtil().setWidth(8),
                ),
                Expanded(
                    child: Container(
                  height: ScreenUtil().setHeight(41),
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius:
                          BorderRadius.circular(ScreenUtil().setWidth(4)),
                      border: Border.all(color: Color(0xffDCDFE6))),
                  child: TextField(
                    keyboardType: TextInputType.number,
                    controller: phoneContr,
                    decoration: InputDecoration(border: InputBorder.none),
                  ),
                )),
                Container(
                  width: ScreenUtil().setWidth(113),
                  height: ScreenUtil().setHeight(41),
                  decoration: redButtonStyle,
                  child: LoginFormCode(
                    textEditingController: phoneContr,
                    onTapCallback: () {
                      requestCode();
                    },
                  ),
                  alignment: Alignment.center,
                )
              ],
            ),
            SizedBox(
              height: ScreenUtil().setHeight(12),
            ),
            Row(
              children: <Widget>[
                Text(
                  "验证码",
                  style: TextStyle(
                      color: textColor10,
                      fontSize: ScreenUtil().setSp(16),
                      fontWeight: FontWeight.bold),
                ),
                SizedBox(
                  width: ScreenUtil().setWidth(8),
                ),
                Expanded(
                    child: Container(
                  height: ScreenUtil().setHeight(41),
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius:
                          BorderRadius.circular(ScreenUtil().setWidth(4)),
                      border: Border.all(color: Color(0xffDCDFE6))),
                  child: TextField(
                    keyboardType: TextInputType.number,
                    controller: virifyContr,
                    decoration: InputDecoration(border: InputBorder.none),
                  ),
                )),
              ],
            ),
            SizedBox(
              height: ScreenUtil().setHeight(12),
            ),
            Row(
              children: <Widget>[
                Text(
                  "群名称",
                  style: TextStyle(
                      color: textColor10,
                      fontSize: ScreenUtil().setSp(16),
                      fontWeight: FontWeight.bold),
                ),
                SizedBox(
                  width: ScreenUtil().setWidth(8),
                ),
                Expanded(
                    child: Container(
                  height: ScreenUtil().setHeight(41),
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius:
                          BorderRadius.circular(ScreenUtil().setWidth(4)),
                      border: Border.all(color: Color(0xffDCDFE6))),
                  child: TextField(
                    keyboardType: TextInputType.number,
                    controller: nameContr,
                    decoration: InputDecoration(border: InputBorder.none),
                  ),
                )),
              ],
            ),
            SizedBox(
              height: ScreenUtil().setHeight(12),
            ),
            Row(
              children: <Widget>[
                Text(
                  "群人数",
                  style: TextStyle(
                      color: textColor10,
                      fontSize: ScreenUtil().setSp(16),
                      fontWeight: FontWeight.bold),
                ),
                SizedBox(
                  width: ScreenUtil().setWidth(8),
                ),
                Expanded(
                    child: Container(
                  height: ScreenUtil().setHeight(41),
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius:
                          BorderRadius.circular(ScreenUtil().setWidth(4)),
                      border: Border.all(color: Color(0xffDCDFE6))),
                  child: TextField(
                    keyboardType: TextInputType.number,
                    controller: numContr,
                    decoration: InputDecoration(border: InputBorder.none),
                  ),
                )),
              ],
            ),
            SizedBox(
              height: ScreenUtil().setHeight(12),
            ),
            Row(
              children: <Widget>[
                Text(
                  "群截图",
                  style: TextStyle(
                      color: textColor10,
                      fontSize: ScreenUtil().setSp(16),
                      fontWeight: FontWeight.bold),
                ),
              ],
            ),
            SizedBox(
              height: ScreenUtil().setHeight(12),
            ),
            buildImge(),
            SizedBox(
              height: ScreenUtil().setHeight(12),
            ),
            GestureDetector(
              child: Container(
                width: ScreenUtil().setWidth(360),
                height: ScreenUtil().setHeight(41),
                alignment: Alignment.center,
                child: Text(
                  "申请智能小助理",
                  style: TextStyle(
                      color: Color(0xffffffff),
                      fontSize: ScreenUtil().setSp(16)),
                ),
                decoration: redButtonStyle,
              ),
              onTap: () {
                if(varify()){
                requestGroup();
                }
//                varify();
              },
            ),
            SizedBox(
              height: ScreenUtil().setHeight(12),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Text(
                  "申请条件：\r\n（1）群名必须含A+标识；\r\n（2）群只能销售A+平台团品；",
                  style: TextStyle(color: textColor10),
                )
              ],
            )
          ],
        ),
      )),
    );
  }

  Widget buildImge() {
    return Row(
      children: <Widget>[
//        Container(
//          alignment: Alignment.center,
//          width: ScreenUtil().setWidth(104),
//          height: ScreenUtil().setHeight(104),
//          decoration: BoxDecoration(
//            color: Color(0xffe5e5e5),
//            borderRadius: BorderRadius.circular(ScreenUtil().setWidth(4)),
//          ),
//          child: Column(
//            mainAxisAlignment: MainAxisAlignment.center,
//            children: <Widget>[
//              Image.asset(
//                "assets/ab.png",
//                width: ScreenUtil().setWidth(20),
//                height: ScreenUtil().setHeight(20),
//              ),
//              SizedBox(
//                height: ScreenUtil().setHeight(10),
//              ),
//              Text(
//                "示例",
//                style: TextStyle(
//                    color: Color(0xff8D9EA7), fontSize: ScreenUtil().setSp(14)),
//              )
//            ],
//          ),
//        ),
//        Container(
//          width: ScreenUtil().setWidth(10),
//        ),
      screenShot.isNotEmpty?GestureDetector(
        child:
        Container(
          alignment: Alignment.center,
          width: ScreenUtil().setWidth(104),
          height: ScreenUtil().setHeight(104),
          child: Image.network(
            screenShot,
            width: ScreenUtil().setWidth(104),
            height: ScreenUtil().setHeight(104),
          ),
        )

        ,
        onTap: (){
          screen = true;
          _onImageButtonPressed(ImageSource.gallery, context: context);
        },

      ):
        GestureDetector(
          child: Container(
            alignment: Alignment.center,
            width: ScreenUtil().setWidth(104),
            height: ScreenUtil().setHeight(104),
            decoration: BoxDecoration(
                color: Color(0xfffafafa),
                borderRadius: BorderRadius.circular(ScreenUtil().setWidth(4)),
                border: Border.all(
                    color: Color(0xffd5d5d5), width: ScreenUtil().setWidth(1))),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Image.asset(
                  "assets/assist/jiahao.png",
                  width: ScreenUtil().setWidth(24),
                  height: ScreenUtil().setHeight(24),
                ),
                SizedBox(
                  height: ScreenUtil().setHeight(15),
                ),
                Text(
                  "团长微信\r\n二维码",
                  style: TextStyle(
                      color: Color(0xff8D9EA7),
                      fontSize: ScreenUtil().setSp(14)),
                )
              ],
            ),
          ),
          onTap: () {
            screen = true;
            _onImageButtonPressed(ImageSource.gallery, context: context);
          },
        ),
        Container(
          width: ScreenUtil().setWidth(10),
        ),
        codeShot.isNotEmpty?GestureDetector(

          child:
          Container(
            alignment: Alignment.center,
            width: ScreenUtil().setWidth(104),
            height: ScreenUtil().setHeight(104),
            child: Image.network(
              codeShot,
              width: ScreenUtil().setWidth(104),
              height: ScreenUtil().setHeight(104),
            ),
          )

          ,
          onTap: (){
            screen = false;
            _onImageButtonPressed(ImageSource.gallery, context: context);
          },

        ):
        GestureDetector(
          child: Container(
            alignment: Alignment.center,
            width: ScreenUtil().setWidth(104),
            height: ScreenUtil().setHeight(104),
            decoration: BoxDecoration(
                color: Color(0xfffafafa),
                borderRadius: BorderRadius.circular(ScreenUtil().setWidth(4)),
                border: Border.all(
                    color: Color(0xffd5d5d5), width: ScreenUtil().setWidth(1))),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Image.asset(
                  "assets/assist/jiahao.png",
                  width: ScreenUtil().setWidth(24),
                  height: ScreenUtil().setHeight(24),
                ),
                SizedBox(
                  height: ScreenUtil().setHeight(15),
                ),
                Text(
                  "入群二维码",
                  style: TextStyle(
                      color: Color(0xff8D9EA7), fontSize: ScreenUtil().setSp(14)),
                )
              ],
            ),
          ),
          onTap: (){
            screen = false;
            _onImageButtonPressed(ImageSource.gallery, context: context);
          },

        )

      ],
    );
  }

  bool varify() {
    if (virifyContr.text.isEmpty) {
      Toast.show(msg: "请输入正确的验证码");
      return false;
    }
    if (nameContr.text.isEmpty) {
      Toast.show(msg: "请输入正确的群名称");
      return false;
    }
    if (!nameContr.text.contains("A+")) {
      Toast.show(msg: "群名称请包含'A+'");
      return false;
    }

    if (screenShot.isEmpty) {
      Toast.show(msg: "请上传团长微信二维码");
      return false;
    }
    if (codeShot.isEmpty) {
      Toast.show(msg: "请上传二维码");
      return false;
    }
    return true;
  }

  void _onImageButtonPressed(ImageSource source, {BuildContext context}) async {
//    if (_controller != null) {
//      await _controller.setVolume(0.0);
//    }
    if (isVideo) {
      final PickedFile file = await _picker.getVideo(
        source: source,
      );
//      Fluttertoast.showToast(msg: "${file.path}", textColor: Colors.black);
//      list.add(DetailTemp("video", file.path, list.length.toString())
//          .setController(VideoPlayerController.file(File(file.path))));
//      await _playVideo(file);
    } else {
      try {
        final pickedFile = await _picker.getImage(
          source: source,
        );
        requestUpload(File(pickedFile.path), true, screen);
//        list.add(DetailTemp("image", pickedFile.path, list.length.toString()));
//        Fluttertoast.showToast(
//            msg: "${pickedFile.path}", textColor: Colors.black);
//        setState(() {
//          _imageFile = pickedFile;
//        });
      } catch (e) {
        setState(() {});
      }
    }
    setState(() {});
  }

  void requestUpload(File file, bool image, bool screen) async {
//    EasyLoading.showSuccess("正在加载……");

  DialogUtil.showloadingdialog(context);
    try {
//        Map<String, dynamic> map = Map<String, dynamic>();

//      map["keyword"] = widget.search;
//      map["page"] = currentPage;

      Map<String, dynamic> map1 = await HttpClient.requestUpload(file, image);
//
      UploadEntity loginEntity = new UploadEntity();

      loginEntity = uploadEntityFromJson(loginEntity, map1);
      DialogUtil.pop(context);

      if (loginEntity.code == null || loginEntity.code != 200) {
//        Fluttertoast.showToast(msg: "null");
        Toast.show(msg: loginEntity.msg);
        return;
      }
      if (loginEntity.code == 200) {
//        Toast.show(msg: "创建成功");
//        NaviUtil.pop(this.context);

//        generateUpload(loginEntity.data, image);
        if (screen) {
          screenShot = loginEntity.data;
        } else {
          codeShot = loginEntity.data;
        }

        setState(() {});
      }
    } catch (e) {
      print(e.toString());
      DialogUtil.pop(context);
    }
  }

  void requestCode() async {
    hasSendCode = true;
    try {
      Map<String, dynamic> map = Map<String, dynamic>();
      map["mobile"] = phoneContr.text;

      Map<String, dynamic> map1 = await HttpClient.requestLogin(
          Config.requestApi + 'member/login/sendSms',
          data: map);

//      PhoneCodeEntity loginEntity = new PhoneCodeEntity();
//
//      loginEntity = phoneCodeEntityFromJson(loginEntity, map1);

//      if (loginEntity.code == null) {
////        Fluttertoast.showToast(msg: "null");
//        return;
//      }
//      if (loginEntity.code == 200) {}
    } catch (e) {
      print(e.toString());
    }
  }

  void requestGroup() async {
//    light/register/index
  DialogUtil.showloadingdialog(context);
    try {
      Map<String, dynamic> map = Map<String, dynamic>();
      map["mobile"] = phoneContr.text;
      map["member_id"] = Constants.memberInfoEntity.data.memberId;
      map["group_name"] = nameContr.text;
      map["number"] = numContr.text;
      map["img_url"] = screenShot;
      map["member_img_url"] = codeShot;
      map["smscode"] = virifyContr.text;

      Map<String, dynamic> map1 = await HttpClient.requestLogin(
          Config.requestApi + 'light/register/index',
          data: map);

      CommonResultEntity loginEntity = new CommonResultEntity();

      loginEntity = commonResultEntityFromJson(loginEntity, map1);
      DialogUtil.pop(context);

      if (loginEntity.code == null || loginEntity.code != 200) {
//        Fluttertoast.showToast(msg: "null");
        Toast.show(msg: loginEntity.msg);
        return;
      }
      if (loginEntity.code == 200) {
        Toast.show(msg: "创建成功");
        NaviUtil.push(context, RegistrySuccess());

      }
    } catch (e) {
      DialogUtil.pop(context);
      print(e.toString());
    }
  }
}
